<?php
/**
 * 创建 IMEI 记录
 * 用于测试 Vendor2 消息
 */

// 定义应用根目录
define('APP_PATH', __DIR__ . '/application/');
define('RUNTIME_PATH', __DIR__ . '/runtime/');

// 加载 ThinkPHP 框架
require __DIR__ . '/thinkphp/base.php';

use think\Db;

$imei = '861179035726231';

echo "========== 创建 IMEI 记录 ==========\n\n";

// 第一步：检查 IMEI 是否已存在
echo "【第一步】检查 IMEI 是否已存在...\n";
try {
    $record = Db::name('flow_wifi_imei')->where('IMEI', $imei)->find();
    if ($record) {
        echo "✅ IMEI 已存在于数据库\n";
        echo "   无需创建\n";
        exit(0);
    } else {
        echo "❌ IMEI 不存在\n";
        echo "   准备创建...\n";
    }
} catch (\Throwable $e) {
    echo "❌ 查询失败: " . $e->getMessage() . "\n";
    exit(1);
}

echo "\n";

// 第二步：创建 IMEI 记录
echo "【第二步】创建 IMEI 记录...\n";
try {
    $result = Db::name('flow_wifi_imei')->insert([
        'IMEI' => $imei,
        'mac' => $imei,
        'update_time' => date('Y-m-d H:i:s')
    ]);
    
    if ($result) {
        echo "✅ IMEI 记录创建成功\n";
    } else {
        echo "❌ IMEI 记录创建失败\n";
        exit(1);
    }
} catch (\Throwable $e) {
    echo "❌ 创建失败: " . $e->getMessage() . "\n";
    exit(1);
}

echo "\n";

// 第三步：验证记录
echo "【第三步】验证记录...\n";
try {
    $record = Db::name('flow_wifi_imei')->where('IMEI', $imei)->find();
    if ($record) {
        echo "✅ 记录验证成功\n";
        echo "   IMEI: " . $record['IMEI'] . "\n";
        echo "   MAC: " . $record['mac'] . "\n";
        echo "   更新时间: " . $record['update_time'] . "\n";
    } else {
        echo "❌ 记录验证失败\n";
        exit(1);
    }
} catch (\Throwable $e) {
    echo "❌ 验证失败: " . $e->getMessage() . "\n";
    exit(1);
}

echo "\n========== 创建完成 ==========\n";
echo "\n现在可以运行测试脚本了:\n";
echo "php test_vendor2_mqtt.php\n";

